package org.jeecg.aop;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.jeecg.annotation.CurDataSource;
import org.jeecg.config.DataSourceNames;
import org.jeecg.config.DynamicDataSource;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
/**
 * 多数据源，切面处理类
 * AOP拦截多数据源注解 @CurDataSource 注解更换数据源
 * @Description: TODO
 * @author: duanlikao
 * @date: 2021年11月24日 15:27
 */



@Slf4j
@Aspect
@Component
public class DataSourceAspect implements Ordered {


    /**
     * 切点
     */
    @Pointcut("@annotation(org.jeecg.annotation.CurDataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        CurDataSource curDataSource = method.getAnnotation(CurDataSource.class);
        if (curDataSource == null) {
            DynamicDataSource.setDataSource(DataSourceNames.FIRST);
            log.info("set datasource is " + DataSourceNames.FIRST);
        } else {
            DynamicDataSource.setDataSource(curDataSource.name());
            log.info("set datasource is " + curDataSource.name());
        }
        try {
            return point.proceed();
        } finally {
            DynamicDataSource.clearDataSource();
            log.info("clean datasource");
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
